
package com.sgcc.nfc.lock.data.repository

import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.core.network.safeApiCall
import com.sgcc.nfc.lock.core.util.DateUtils
import com.sgcc.nfc.lock.data.remote.api.LockApi
import com.sgcc.nfc.lock.data.remote.api.LogApi
import com.sgcc.nfc.lock.data.remote.api.RoomApi
import com.sgcc.nfc.lock.data.remote.api.WarningApi
import com.sgcc.nfc.lock.domain.model.DashboardStats
import com.sgcc.nfc.lock.domain.model.StatItem
import com.sgcc.nfc.lock.domain.model.TrendData
import com.sgcc.nfc.lock.domain.model.TrendDirection
import com.sgcc.nfc.lock.domain.repository.DashboardRepository
import javax.inject.Inject
import kotlin.random.Random

class DashboardRepositoryImpl @Inject constructor(
    private val lockApi: LockApi,
    private val warningApi: WarningApi,
    private val roomApi: RoomApi,
    private val logApi: LogApi
) : DashboardRepository {

    override suspend fun getDashboardStats(): NetworkResult<DashboardStats> {
        val totalLocks = safeApiCall {
            lockApi.getLocks(pageNum = 1, pageSize = 1)
        }
        val openLocks = safeApiCall {
            lockApi.getLocks(pageNum = 1, pageSize = 1, status = 1)
        }
        val closedLocks = safeApiCall {
            lockApi.getLocks(pageNum = 1, pageSize = 1, status = 0)
        }
        val pendingWarnings = safeApiCall {
            warningApi.getWarnings(pageNum = 1, pageSize = 1, status = 0)
        }
        val rooms = safeApiCall {
            roomApi.getRooms(pageNum = 1, pageSize = 1)
        }
        val logs = safeApiCall {
            logApi.getLogs(
                pageNum = 1,
                pageSize = 1,
                startTime = DateUtils.todayStart(),
                endTime = DateUtils.todayEnd()
            )
        }

        if (listOf(totalLocks, openLocks, closedLocks, pendingWarnings, rooms, logs).any { it is NetworkResult.Error }) {
            val error = (listOf(totalLocks, openLocks, closedLocks, pendingWarnings, rooms, logs)
                .filterIsInstance<NetworkResult.Error>()
                .firstOrNull())
            return error ?: NetworkResult.Error(-1, "统计信息加载失败")
        }

        val totalLocksCount = (totalLocks as? NetworkResult.Success)?.data?.total?.toInt() ?: 0
        val openLocksCount = (openLocks as? NetworkResult.Success)?.data?.total?.toInt() ?: 0
        val closedLocksCountFromApi = (closedLocks as? NetworkResult.Success)?.data?.total?.toInt()
        val closedLocksCount = closedLocksCountFromApi ?: (totalLocksCount - openLocksCount).coerceAtLeast(0)

        val stats = DashboardStats(
            totalLocks = StatItem(totalLocksCount, generateMockTrend()),
            openLocks = StatItem(openLocksCount, generateMockTrend()),
            closedLocks = StatItem(closedLocksCount, generateMockTrend()),
            pendingWarnings = StatItem((pendingWarnings as? NetworkResult.Success)?.data?.total?.toInt() ?: 0, generateMockTrend()),
            totalRooms = StatItem((rooms as? NetworkResult.Success)?.data?.total?.toInt() ?: 0, generateMockTrend()),
            todayOperations = StatItem((logs as? NetworkResult.Success)?.data?.total?.toInt() ?: 0, generateMockTrend())
        )
        return NetworkResult.Success(stats)
    }

    /**
     * 生成模拟趋势数据
     * 在实际项目中，这些数据应该从后端API获取
     */
    private fun generateMockTrend(): TrendData {
        val directions = TrendDirection.values()
        val direction = directions[Random.nextInt(directions.size)]
        val percentage = Random.nextDouble(0.1, 25.0)
        
        return TrendData(
            direction = direction,
            percentage = percentage
        )
    }
}
